import { useGlobalStore } from '@/store'
import useAxureConfig from './useAxureConfig'
import useMainInvoke from './useMainInvoke'

export default function useAxureDoc(
  projectId: string,
  storePath: string,
  filename: string | null,
  onprogess: (statusText: string, done: boolean) => void
): Promise<{ doc: TreeItem[] | TransformItem[]; isCache: boolean; isUpdated: boolean }> {
  const { originalFile, updatedFile } = useGlobalStore()
  const isFromCache = [originalFile, updatedFile].includes(filename!)

  return new Promise((resolve, reject) => {
    const removeListener = window.electron.ipcRenderer.on(
      'main-to-renderer',
      (_, { name, docStr, isCache, error }) => {
        if (name === 'error' && error) {
          reject(error)
          return
        }

        // prettier-ignore
        switch (name) {
          case 'fetch-start': onprogess('获取文档中...', false); break
          case 'fetch-done': onprogess('文档已获取', false); break
          case 'create-start': onprogess('储存当前文档数据中...', false); break
          case 'create-done': {
            onprogess(isCache ? '已从本地读取文档' : '文档已创建', true);

            const originalTree = JSON.parse(docStr) as TreeItem[] | TransformItem[]

            resolve({ doc: originalTree, isCache: isFromCache, isUpdated: filename === updatedFile })

            removeListener()

            break
          }
          default: break;
        }
      }
    )

    const { docUrl, prefix, suffix } = useAxureConfig(projectId)
    // 是否在有数据记录是仍要重新获取
    const rewrite = !filename
    // 在浏览器中使用 fetch 进行跨域请求无法获取数据，即使服务器返回了响应数据
    // 只能将对应的域名发送给主线程进行请求
    useMainInvoke('file', 'create-doc', {
      projectId,
      storePath,
      url: docUrl,
      prefix,
      suffix,
      filename: filename || `original_tree_${projectId}.json`,
      rewrite
    })
  })
}
